package com.handa.admin.userservice.service.impl;

import com.handa.admin.userservice.common.entity.LoginUser;
import com.handa.admin.userservice.entity.VO.OnlineSysUserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Service
public class UserOnlineService {
    private static final String DAILY_ONLINE_KEY_PREFIX = "daily_online_users:";
    private final RedisTemplate<String, String> redisTemplate;

    @Autowired
    public UserOnlineService(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * 记录用户上线
     */
    public void userLogin(LoginUser loginUser) {
        userLogin(loginUser, LocalDate.now());
    }

    public void userLogin(LoginUser loginUser, LocalDate date) {

        String msg = loginUser.getUserId() + ":" + loginUser.getUsername() +
                ":" + loginUser.getNickname();

        String todayKey = getKeyByDate(date);
        redisTemplate.opsForSet().add(todayKey, msg);

        // 可选：设置过期时间(保留30天数据)
        redisTemplate.expire(todayKey, 90, TimeUnit.DAYS);
    }

    /**
     * 获取某日所有在线用户列表
     *
     * @param date 查询日期
     * @return 用户ID集合
     */
    public Set<OnlineSysUserVO> getDailyOnlineUsers(LocalDate date) {
        String key = getKeyByDate(date);
        Set<String> members = redisTemplate.opsForSet().members(key);

        Set<OnlineSysUserVO> res = new HashSet<>();
        for (String member : members) {
            String[] parts = member.split(":");
            if (parts.length == 3) {
                OnlineSysUserVO onlineSysUserVO = new OnlineSysUserVO();
                onlineSysUserVO.setUserId(parts[0]);
                onlineSysUserVO.setUsername(parts[1]);
                onlineSysUserVO.setNickname(parts[2]);

                res.add(onlineSysUserVO);
            }

        }

        return res;
    }

    /**
     * 获取某日在线用户数量
     *
     * @param date 查询日期
     * @return 在线用户数
     */
    public Long getDailyOnlineUserCount(LocalDate date) {
        String key = getKeyByDate(date);
        return redisTemplate.opsForSet().size(key);
    }

    public List<Long> getDailyOnlineUsersCount(List<LocalDate> dates) {
        List<Long> res = new ArrayList<>();
        dates.forEach(item -> {
            String key = getKeyByDate(item);
            res.add(redisTemplate.opsForSet().size(key));
        });
        return res;
    }

    /**
     * 检查用户某日是否在线
     *
     * @param userId 用户ID
     * @param date   查询日期
     * @return 是否在线
     */
    public boolean isUserOnlineOnDate(String userId, LocalDate date) {
        String key = getKeyByDate(date);
        return Boolean.TRUE.equals(redisTemplate.opsForSet().isMember(key, userId));
    }

    private String getKeyByDate(LocalDate date) {
        return DAILY_ONLINE_KEY_PREFIX + date.format(DateTimeFormatter.BASIC_ISO_DATE);
    }
}